package com.qut.graduate.busrtquery.ui.common;

import android.Manifest;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.BitmapDrawable;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.NonNull;
import android.support.design.widget.Snackbar;
import android.util.Log;
import android.view.View;
import android.widget.Button;

import com.qut.graduate.busrtquery.BRTQConstant;
import com.qut.graduate.busrtquery.BaseActivity;
import com.qut.graduate.busrtquery.R;
import com.qut.graduate.busrtquery.bean.Advertisement;
import com.qut.graduate.busrtquery.bean.User;
import com.qut.graduate.busrtquery.ui.MainActivity;
import com.qut.graduate.busrtquery.utils.common.LogUtils;
import com.qut.graduate.busrtquery.utils.common.PermissionUtils;
import com.qut.graduate.busrtquery.utils.photoselect.FileUtils;
import com.qut.graduate.busrtquery.utils.uiabout.StatusBarUtils;
import com.qut.graduate.busrtquery.utils.uiabout.ToastColorfulUtils;
import com.qut.graduate.busrtquery.view.AutoZoomInImageView;

import java.io.File;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;

import cn.bmob.v3.BmobQuery;
import cn.bmob.v3.BmobUser;
import cn.bmob.v3.datatype.BmobFile;
import cn.bmob.v3.exception.BmobException;
import cn.bmob.v3.listener.DownloadFileListener;
import cn.bmob.v3.listener.FindListener;

public class SplashActivity extends BaseActivity implements View.OnClickListener {
    private static final String TAG = "SplashActivity";
    private AutoZoomInImageView autoZoomInImageView;
    private Button mJumpBtn;

    private String[] permissions = new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.READ_EXTERNAL_STORAGE,
            Manifest.permission.ACCESS_COARSE_LOCATION, Manifest.permission.ACCESS_FINE_LOCATION,
            Manifest.permission.READ_PHONE_STATE, Manifest.permission.CAMERA};
    private static final long DELAY_TIME = 3000L;
    private int recLen = 3; // 跳过倒计时提示3秒
    Timer timer = new Timer();
    private Handler handler;
    private Runnable runnable;

    @Override
    protected int getLayoutId() {
        return R.layout.activity_splash;
    }

    @Override
    protected void init() {
        StatusBarUtils.setStatusBarTransparent(this);
        initView();
        initEvent();
    }

    private void initView() {
        mJumpBtn = findViewById(R.id.splash_jump_btn);
        autoZoomInImageView = findViewById(R.id.splash_adImage);
        mJumpBtn.setOnClickListener(this);
    }

    private void initEvent() {
        if (PermissionUtils.checkPermission(this, BRTQConstant.PERMISSION_CODE_CHECK, permissions)) {
            loadAd();
        } else {
            requestPermission();
        }
    }

    /**
     * 加载广告
     */
    public void loadAd() {
        // 判断是否是第一次开启应用
        boolean isFirstOpen = preferenceUtils.getIsFirstOpenApp();
        // 如果是第一次启动，则先加载本地图片，并下载bmob服务器的广告图片保存其本地图片地址并在下次加载该图片
        if (isFirstOpen) {
            preferenceUtils.setIsFirstOpenApp(false);
        } else {
            String path = preferenceUtils.getString(getString(R.string.preference_ad_image_path), "");
            if (path != null && !path.equals("")) {
                Bitmap adBitmap = BitmapFactory.decodeFile(path);
                BitmapDrawable adDrawable = new BitmapDrawable(getResources(), adBitmap);
                autoZoomInImageView.setImageBitmap(adBitmap);
            }
        }
        adImageZoomIn();
        queryAdImageName();
        timer.schedule(task, 1000, 1000); // 等待时间一秒，停顿时间一秒
        redirectByTime();
    }

    public void adImageZoomIn() {
        autoZoomInImageView.post(new Runnable() {
            @Override
            public void run() {
                autoZoomInImageView.init().setScaleDelta(0.4f) // 放大的系数是原来的（1 + 0.3）倍
                        .setDurationMillis(2500) // 动画的执行时间为2500毫秒
                        .start(0); // 延迟1000毫秒启动
            }
        });
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.splash_jump_btn:
                gotoMainActivity();
                if (runnable != null)
                    handler.removeCallbacks(runnable);
                break;
        }
    }

    /**
     * 倒计时
     */
    private void redirectByTime() {
        handler = new Handler();
        handler.postDelayed(runnable = new Runnable() {
            @Override
            public void run() {
                gotoMainActivity();
            }
        }, DELAY_TIME);
    }

    TimerTask task = new TimerTask() {
        @Override
        public void run() {
            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    recLen--;
                    mJumpBtn.setText(recLen + "s\t\t跳过");
                    if (recLen <= 0) {
                        timer.cancel();
                        mJumpBtn.setVisibility(View.GONE);
                    }
                }
            });
        }
    };

    /**
     * 跳转到主页
     */
    public void gotoMainActivity() {
        Intent intent = new Intent(SplashActivity.this, MainActivity.class);
        startActivity(intent);
        finish();
    }

    /**
     * 获取权限
     */
    public boolean requestPermission() {
        boolean isHavePermission = PermissionUtils.checkPermissionFirst(this,
                BRTQConstant.PERMISSION_CODE_FIRST, permissions);
        return isHavePermission;
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if (requestCode == BRTQConstant.PERMISSION_CODE_FIRST) {
            loadAd();
        }
    }

    /**
     * 查询bmob上id为“1”的广告图片的名字
     */
    private void queryAdImageName() {
        BmobQuery<Advertisement> categoryBmobQuery = new BmobQuery<>();
        categoryBmobQuery.addWhereEqualTo("id", "1");
        categoryBmobQuery.findObjects(new FindListener<Advertisement>() {
            @Override
            public void done(List<Advertisement> object, BmobException e) {
                if (e == null) {
                    String imageName = preferenceUtils.getString(getString(R.string.preference_ad_image_name), "");
                    if (object != null && object.size() > 0) {
                        LogUtils.d("bmob 查询广告成功 bmob图片名称：" + object.get(0).getImage().getFilename());
                        LogUtils.d("bmob 查询广告成功 本地图片名称：" + imageName);
                        if (!imageName.equals(object.get(0).getImage().getFilename())) {
                            downloadAdImage(object.get(0).getImage());
                        }
                    }
                } else {
                    LogUtils.d("bmob 查询广告失败：" + e.toString());
                }
            }
        });
    }

    /**
     * 下载广告图片
     *
     * @param image
     */
    public void downloadAdImage(BmobFile image) {
        //允许设置下载文件的存储路径，默认下载文件的目录为：context.getApplicationContext().getCacheDir()+"/bmob/"
        if (image != null) {
            FileUtils.createOrExistsDir(BRTQConstant.AD_DOWNLOAD_DIR);
            final File saveFile = new File(BRTQConstant.AD_DOWNLOAD_DIR, image.getFilename());
            image.download(saveFile, new DownloadFileListener() {
                @Override
                public void onStart() {
                    LogUtils.d("bmob 开始下载广告图片...", this.getClass());
                }

                @Override
                public void done(String savePath, BmobException e) {
                    if (e == null) {
                        LogUtils.d("bmob 广告图片下载成功,保存路径:" + savePath, this.getClass());
                        String pictureName = savePath.substring(savePath.lastIndexOf("/") + 1);
                        preferenceUtils.putString(getString(R.string.preference_ad_image_name), pictureName);
                        preferenceUtils.putString(getString(R.string.preference_ad_image_path), savePath);
                    } else {
                        LogUtils.d("bmob 广告图片下载失败：" + e.getErrorCode() + ", " + e.getMessage());
                    }
                }

                @Override
                public void onProgress(Integer value, long newworkSpeed) {
                    LogUtils.d("bmob 广告图片下载进度：" + value + ", " + newworkSpeed);
                }
            });
        }
    }

}
